package com.yunst.net.protocol;

import com.yunst.net.message.EventMessage;
import com.yunst.net.message.ImageMessage;
import com.yunst.net.message.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.ReplayingDecoder;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.List;

/**
 * @author yunst
 * @date 2022/12/31
 */
public class MessageDecode extends ReplayingDecoder<Void> {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int length = byteBuf.readInt();
        int type = byteBuf.readInt();
        byte[] content = new byte[length];

        byteBuf.readBytes(content);
        switch (type) {
            case 0:
                ImageMessage imageMessage = new ImageMessage();
                imageMessage.setLen(length);
                imageMessage.setContent(content);
                list.add(imageMessage);
                break;
            case 1:
                EventMessage eventMessage = new EventMessage();
                eventMessage.setLen(length);
                eventMessage.setContent(content);
                list.add(eventMessage);
                break;
        }
    }
}
